//
//  MallCollectViewController.m
//  yimei
//
//  Created by Macx on 2018/1/30.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "MallCollectViewController.h"
#import "MallsCollectionViewCell.h"
#import "MallDetailViewController.h"
#import "Goods.h"

@interface MallCollectViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@end

@implementation MallCollectViewController {
    
    UICollectionView *_collectionView;
    CGFloat         _collectionW;
    CGFloat         _collectionH;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self GETMallsGoods];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    
    [self GETMallsGoods];
    
    [self createUI];
    
    [self refreshData];
}

#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.navigationItem.title = @"我的收藏";
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    // collectionView
    
    // 集合视图 collectionView所有布局的父类
    // 系统提供自带的布局类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 默认为纵向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    
    // 创建collectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height-64) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = UISeparatedColorRGB;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"MallsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    
    CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)];
    _collectionW = (SCREEN_WIDTH-30)/2;
    _collectionH = _collectionW+20+size1.height*3;
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MallsCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.infoArr[indexPath.row];
    return item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
        return CGSizeMake(_collectionW, _collectionH);
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    Goods *model = self.infoArr[indexPath.row];
    
    MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
    detailVC.goodId = model.goods_id;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}
#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETMallsGoods];
    }];
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETMallsGoods];
    }];
    
}

#pragma mark ===========响应方法==========
- (void)GETMallsGoods {
    
    
    // GET /malls/goods 获取商品 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 orderby 排序字段 price（价格，默认），sold_num（销量），comments_count（评价数）direction 排序方式 desc（降序，默认）asc（升序）
    
    NSDictionary *param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page]};
    
    [[NetworkTool sharedTool] requestWithName:@"我的收藏" URLString:APIUsersCollected parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        for (NSDictionary *dic in arr) {
            Goods *model = [[Goods alloc] init];
            [model setValuesForKeysWithDictionary:dic[@"goods"]];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
        });
        
    }];
}
// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
